package junmo.s3caesar.mandu.nhkradionews.data;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class NewsFinder {
	
	private String rss;
	
	public NewsFinder(String rss) {
		this.rss = rss;
	}
	
	private Document findDocument() {

		Document document = null;
		try {
			URL urlForHttp = new URL(this.rss);
			HttpURLConnection conn = (HttpURLConnection) urlForHttp.openConnection();
			if(conn != null) {
				conn.setConnectTimeout(10000);
				conn.setRequestMethod("GET");
				conn.setDoInput(true);
				conn.setDoOutput(true);
				if(conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
					InputStream instream = conn.getInputStream();
					document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(instream);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return document;
	}
	
	public List<News> findNewsList() {

		List<News> newsList = new ArrayList<News>();
		Document document = findDocument();
		if(document != null) {
			Element docEle = document.getDocumentElement();
			NodeList nodelist = docEle.getElementsByTagName("item");
			
			if(nodelist != null && nodelist.getLength() > 0) {
				for(int i=0; i<nodelist.getLength(); i++) {
					Element entry = (Element) nodelist.item(i);
					String title = entry.getElementsByTagName("title").item(0).getFirstChild().getNodeValue();
					String pubDate = entry.getElementsByTagName("pubDate").item(0).getFirstChild().getNodeValue();
					String enclosureUrl = entry.getElementsByTagName("enclosure").item(0).getAttributes().getNamedItem("url").getNodeValue(); 
					News item = new News();
					item.setTitle(title);
					item.setPubDate(pubDate);
					item.setEnclosureUrl(enclosureUrl);
					newsList.add(item);
				}
			}
		}
		return newsList;
	}
	
	public String findLastBuildDate() {
		
		String lastBuildDate = "";
		Document document = findDocument();
		if(document != null) {
			Element docEle = document.getDocumentElement();
			NodeList nodelist = docEle.getElementsByTagName("lastBuildDate");
			
			if(nodelist != null && nodelist.getLength() > 0) {
				Element entry = (Element) nodelist.item(0);
				lastBuildDate = entry.getFirstChild().getNodeValue();
			}
		}
		return lastBuildDate;
	}
	
}
